package org.example.backend.controller;

import org.example.backend.dto.PolicyInfoDTO;
import org.example.backend.service.PolicyInfoService;
import org.example.backend.service.LabelService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api/policy")
public class PolicyInfoController {

    private final PolicyInfoService policyInfoService;
    private final LabelService labelService;

    public PolicyInfoController(PolicyInfoService policyInfoService, LabelService labelService) {
        this.policyInfoService = policyInfoService;
        this.labelService = labelService;
    }

    @GetMapping("/{id}")
    public org.springframework.http.ResponseEntity<PolicyInfoDTO> getPolicy(@PathVariable String id) {
        PolicyInfoDTO dto = policyInfoService.getPolicyById(id);
        if (dto == null) {
            return org.springframework.http.ResponseEntity.notFound().build();
        }
        return org.springframework.http.ResponseEntity.ok(dto);
    }

    /**
     * 返回分页后的政策列表，默认每页10条，可通过参数 page/size 控制
     */
    @GetMapping("/all")
    public java.util.Map<String, Object> getAll(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        // 参数验证：确保 page 和 size 都为正数
        if (page < 1) page = 1;
        if (size < 1) size = 10;
        
        org.example.backend.dto.PageResult<PolicyInfoDTO> pageResult = policyInfoService.getPoliciesByPage(page, size, null, null, null, null, null, null, null, null, "publishTime", "desc");
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("list", pageResult.getData());
        result.put("total", pageResult.getTotal());
        return result;
    }

    @GetMapping("/filter")
    public java.util.Map<String, Object> filterPolicies(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) String region,
            @RequestParam(required = false) String dateFrom,
            @RequestParam(required = false) String dateTo,
            @RequestParam(required = false) String tags,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        // 参数验证：确保 page 和 size 都为正数
        if (page < 1) page = 1;
        if (size < 1) size = 10;
        
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        try {
            List<String> tagList = null;
            if (tags != null && !tags.trim().isEmpty()) {
                tagList = java.util.Arrays.asList(tags.split(","))
                        .stream()
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .collect(java.util.stream.Collectors.toList());
            }
            org.example.backend.dto.PageResult<PolicyInfoDTO> pageResult = policyInfoService.getPoliciesByPage(page, size, keyword, category, department, region, dateFrom, dateTo, tagList, status, "publishTime", "desc");
            result.put("list", pageResult.getData());
            result.put("total", pageResult.getTotal());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("list", java.util.Collections.emptyList());
            result.put("total", 0);
            return result;
        }
    }

    // 新增：关键字模糊查询接口
    @GetMapping("/search")
    public List<PolicyInfoDTO> searchByKeyword(@RequestParam String keyword) {
        try {
            return policyInfoService.fuzzySearchPolicies(keyword);
        } catch (Exception e) {
            e.printStackTrace();
            return java.util.Collections.emptyList();
        }
    }

    // 新增：获取相关政策接口
    @GetMapping("/related")
    public List<PolicyInfoDTO> getRelatedPolicies(@RequestParam String id, @RequestParam(defaultValue = "6") int limit) {
        try {
            return policyInfoService.getRelatedPolicies(id, limit);
        } catch (Exception e) {
            e.printStackTrace();
            return java.util.Collections.emptyList();
        }
    }

    // 分页查询接口
    @GetMapping("/page")
    public org.example.backend.dto.PageResult<PolicyInfoDTO> getPoliciesByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) String region,
            @RequestParam(required = false) String dateFrom,
            @RequestParam(required = false) String dateTo,
            @RequestParam(required = false) String tags,
            @RequestParam(required = false) String status,
            @RequestParam(required = false, defaultValue = "publishTime") String sortBy,
            @RequestParam(required = false, defaultValue = "desc") String sortOrder
    ) {
        List<String> tagList = null;
        if (tags != null && !tags.trim().isEmpty()) {
            tagList = java.util.Arrays.asList(tags.split(","))
                    .stream()
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .collect(java.util.stream.Collectors.toList());
        }
        return policyInfoService.getPoliciesByPage(page, size, keyword, category, department, region, dateFrom, dateTo, tagList, status, sortBy, sortOrder);
    }

        /**
     * 获取所有标签数据，包括GB和ZX分类
     */
    @GetMapping("/all-labels")
    public java.util.Map<String, Object> getAllLabels() {
        try {
            return labelService.getAllLabels();
        } catch (Exception e) {
            System.err.println("获取标签数据失败: " + e.getMessage());
            e.printStackTrace();
            // 返回空的标签数据结构，避免前端报错
            java.util.Map<String, Object> emptyResult = new java.util.HashMap<>();
            java.util.Map<String, Object> gbLabels = new java.util.HashMap<>();
            gbLabels.put("level1", new java.util.ArrayList<>());
            gbLabels.put("level2", new java.util.ArrayList<>());
            java.util.Map<String, Object> zxLabels = new java.util.HashMap<>();
            zxLabels.put("level1", new java.util.ArrayList<>());
            zxLabels.put("level2", new java.util.ArrayList<>());
            emptyResult.put("gb", gbLabels);
            emptyResult.put("zx", zxLabels);
            return emptyResult;
        }
    }

    /**
     * 批量获取政策详细信息用于对比
     */
    @PostMapping("/batch")
    public List<PolicyInfoDTO> getBatchPolicies(@RequestBody List<String> policyIds) {
        try {
            System.out.println("批量获取政策详情，IDs: " + policyIds);
            return policyInfoService.getBatchPoliciesByIds(policyIds);
        } catch (Exception e) {
            System.err.println("批量获取政策失败: " + e.getMessage());
            e.printStackTrace();
            return java.util.Collections.emptyList();
        }
    }

    /**
     * 获取政策统计信息用于对比分析
     */
    @PostMapping("/statistics")
    public java.util.Map<String, Object> getPolicyStatistics(@RequestBody List<String> policyIds) {
        try {
            System.out.println("获取政策统计信息，IDs: " + policyIds);
            return policyInfoService.getPolicyStatisticsForComparison(policyIds);
        } catch (Exception e) {
            System.err.println("获取政策统计信息失败: " + e.getMessage());
            e.printStackTrace();
            return new java.util.HashMap<>();
        }
    }

    /**
     * 获取政策地理分布数据
     */
    @PostMapping("/geo-distribution")
    public java.util.Map<String, Object> getPolicyGeoDistribution(@RequestBody List<String> policyIds) {
        try {
            System.out.println("获取政策地理分布，IDs: " + policyIds);
            return policyInfoService.getPolicyGeoDistribution(policyIds);
        } catch (Exception e) {
            System.err.println("获取政策地理分布失败: " + e.getMessage());
            e.printStackTrace();
            return new java.util.HashMap<>();
        }
    }
}
